package com.gemme.gemme.util;

import android.content.Context;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.common.OSSConstants;
import com.alibaba.sdk.android.oss.common.auth.OSSAuthCredentialsProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSFederationToken;
import com.alibaba.sdk.android.oss.common.utils.IOUtils;
import com.gemme.gemme.manager.DataManager;

import org.json.JSONObject;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class MyOSSAuthCredentialsProvider extends OSSAuthCredentialsProvider {
    private OSSAuthCredentialsProvider oosProvide;
    private String authServerUrl;
    private Context context;

    public MyOSSAuthCredentialsProvider(String authServerUrl , Context context) {
        super(authServerUrl);
        this.oosProvide = new OSSAuthCredentialsProvider(authServerUrl);
        this.authServerUrl = authServerUrl;
        this.context = context;
    }

    @Override
    public OSSFederationToken getFederationToken() throws ClientException {
        OSSFederationToken authToken;
        String authData;
        try {
//            URL stsUrl = new URL(mAuthServerUrl);
            URL stsUrl = new URL(authServerUrl);
            HttpURLConnection conn = (HttpURLConnection) stsUrl.openConnection();
//            conn.setRequestProperty("Authorization","Bearer a46cc96f-5337-4742-84ee-1131b83d9cb7");
            conn.setRequestProperty("Authorization", DataManager.getToken(context));
            conn.setConnectTimeout(10000);
            InputStream input = conn.getInputStream();
            authData = IOUtils.readStreamAsString(input, OSSConstants.DEFAULT_CHARSET_NAME);
            if (ReflectionUtils.getPrivateField(oosProvide, "mDecoder") != null) {
                authData = ((AuthDecoder)(ReflectionUtils.getPrivateField(oosProvide, "mDecoder"))).decode(authData);
            }
            String oss = (new JSONObject(authData)).getString("data");
            JSONObject jsonObj = new JSONObject(oss);
            int statusCode = jsonObj.getInt("StatusCode");
            if (statusCode == 200) {
                String ak = jsonObj.getString("AccessKeyId");
                String sk = jsonObj.getString("AccessKeySecret");
                String token = jsonObj.getString("SecurityToken");
                String expiration = jsonObj.getString("Expiration");
                authToken = new OSSFederationToken(ak, sk, token, expiration);
            } else {
                String errorCode = jsonObj.getString("ErrorCode");
                String errorMessage = jsonObj.getString("ErrorMessage");
                throw new ClientException("ErrorCode: " + errorCode + "| ErrorMessage: " + errorMessage);
            }
            return authToken;
        } catch (Exception e) {
            throw new ClientException(e);
        }
    }
}
